package com.sz.app.supplier.web.security;

import com.sz.biz.app.web.security.AbstractCredentialsMatcher;
import com.sz.biz.app.web.security.MyAuthenticationInfo;
import com.sz.biz.common.sup.service.SupplierUserService;
import com.sz.common.base.constants.UserActions;
import com.sz.common.core.service.PrincipalLogUtils;
import com.sz.common.core.service.PrincipalManager;
import com.sz.app.supplier.constants.ModuleNames;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.cache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;


public class SupplierHashedCredentialsMatcher extends
        AbstractCredentialsMatcher {

    @Autowired
    SupplierUserService supplierUserService;

    @Autowired
    private PrincipalManager principalManager;

    public SupplierHashedCredentialsMatcher(CacheManager cacheManager) {
        super(cacheManager);
    }

    @Override
    protected void lockUser(int accountId, String accountName) {
        List<Integer> accountList = new ArrayList<>();
        accountList.add(accountId);
        supplierUserService.lockSupplierUser(accountList);

        passwordRetryCache.remove(accountName);
        PrincipalLogUtils.addOperationLog(ModuleNames.SUP, ModuleNames.SUPPLIER_LOGIN, UserActions.LOCK,
                accountName + "输入错误次数过多，被系统锁定");
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token,
                                      AuthenticationInfo info) {

        if (!(info instanceof MyAuthenticationInfo)) {
            throw new RuntimeException("No supported AuthenticationInfo");
        }
        MyAuthenticationInfo myInfo = (MyAuthenticationInfo) info;

        int accountId = myInfo.getAccountId();
        String accountName = myInfo.getAccountName();

        //对比密码
        boolean matches = super.doCredentialsMatch(token, info);
        if (matches) {
            //如果正确，清除之前连续错误的计数
            passwordRetryCache.remove(accountName);
            principalManager.setupPrincipal(myInfo.getAppDomain(), accountId,
                    myInfo.getAccountName(), myInfo.getProperties());
            return true;
        }
        return false;
    }

    @Override
    protected String getPasswordRetryCacheName() {
        return "passwordRetryCache-supplier";
    }
}
